package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.ChildrenCache;
import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseChildrenCallback;

public class MasterTasksGetChildrenCallback extends BaseChildrenCallback {
	private static final Logger LOGGER = Logger.getLogger(MasterTasksGetChildrenCallback.class);
	private Master master;
	
	public MasterTasksGetChildrenCallback(Master master) {
		this.master = master;
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		master.monitorTasks();
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		List<String> toProcess;
		if(master.getTasksCache()==null) {
			master.setTasksCache(new ChildrenCache(children));
			toProcess = children;
		} else {
			//检测是否有新的待执行任务添加进来
			toProcess = master.getTasksCache().addedAndSet(children);
		}
		
		if(toProcess!=null) {
			//随机选择worker进行分配任务
			assignTasks(toProcess);
		}
	}
	
	private void assignTasks(List<String> tasks) {
		for(String task : tasks) {
			master.getTaskData(task);
		}
	}

	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			List<String> children) {
		LOGGER.error("getChildren failed.",  
                KeeperException.create(Code.get(rc), path));
	}
}
